JAVA线程锁lock下Condition高级使用-多个Condition的整合使用
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 利用多个Condition来实现一个可阻塞的缓冲区 * @author duwenlei * */ public class BoundedBuffer { private final Lock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); final Object[] items = new Object[100]; int putptr,takeptr,count; public void put(Object x) throws InterruptedException{ lock.lock(); try { while (count == items.length) { notFull.await(); //已经满了,等待 } items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; notEmpty.signal();//可以取了 }finally{ lock.unlock(); } } public Object take() throws InterruptedException{ Object obj = null; lock.lock(); try { while(count == 0){ notEmpty.await(); //已经空了,等待 } obj = items[takeptr]; if(++takeptr == items.length) takeptr=0; --count; notFull.signal(); return obj; }finally{ lock.unlock(); } } }
如果有使用请标明来源:http://www.cnblogs.com/duwenlei/